package ru.svi.bluetooth;

import java.util.ArrayList;
import java.util.Set;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class BlueToothThingActivity extends Activity
{
	// Message types sent from the BluetoothChatService Handler
	public static final int MESSAGE_STATE_CHANGE = 1;
	public static final int MESSAGE_READ = 2;
	public static final int MESSAGE_WRITE = 3;
	public static final int MESSAGE_CONNECTED = 4;
	public static final int MESSAGE_CONNECTION_FAILED = 5;
	public static final int MESSAGE_CONNECTION_LOST = 0;
	// Key names received from the BluetoothChatService Handler
	public static final String DEVICE_NAME = "device_name";
	public static final String DEVICE = "Device";

	// Intent request codes
	private static final int REQUEST_SELECT_DEVICE=2;
	private static final int REQUEST_ENABLE_BT = 3;
	public static final String EXTRA_DEVICE = "device";
	protected static final int ATTEMPS = 3; //ATTEMPS to connect


	private TextView textOutput;
	
	private BluetoothAdapter mBluetoothAdapter = null;
	private BluetoothService mService = null;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.main);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.custom_title);

		textOutput = (TextView) findViewById(R.id.textViewOutput);
		mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		if (mBluetoothAdapter == null) {
			Toast.makeText(this, "There is no Bluetooth adapter on this device", Toast.LENGTH_LONG).show();
			finish();
			return;
		}

		Button getInfoButton = (Button) findViewById(R.id.buttonCommunicate);
		getInfoButton.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {
				if (!mBluetoothAdapter.isEnabled()) {			
					Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
					startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
				} else	
					getInfo();
			}
		});
		
		mService = new BluetoothService(this, mHandler);
	}

	private void getInfo() {		
		if(mService.getState()==BluetoothService.STATE_CONNECTED){
			mService.recieveAgain();
		}
		else{
			Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

			if (pairedDevices.size() > 0)
				chooseFromBound(pairedDevices);
			else
				findDiscoverable();			
		}	

	}

	private void findDiscoverable() {
		Intent intent = new Intent(this,DiscoveryDeviceActivity.class);
		startActivityForResult(intent, REQUEST_SELECT_DEVICE);
	}

	private void chooseFromBound(Set<BluetoothDevice> pairedDevices) {
		if (pairedDevices.size() == 1)
			startCommunication(pairedDevices.iterator().next());
		else {
			Intent intent = new Intent(this,PairedDevicesActivity.class);
			ArrayList<BluetoothDevice> correctDevices = new ArrayList<BluetoothDevice>();
			for(BluetoothDevice device:pairedDevices){
				if(ValidateName.validate(device))
					correctDevices.add(device);
			}
			BluetoothDevice[] dbs = correctDevices.toArray(new BluetoothDevice[]{});
			intent.putExtra(PairedDevicesActivity.EXTRA_PAIRED_DEVICES, dbs);
			startActivityForResult(intent, REQUEST_SELECT_DEVICE);
		}
	}

	private void startCommunication(BluetoothDevice device) {
		mService.receiveData(device);
	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		// Stop the Bluetooth chat services
		if (mService != null)
			mService.stop();
	}

	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case REQUEST_ENABLE_BT:
			// When the request to enable Bluetooth returns
			if (resultCode == Activity.RESULT_OK) {
				getInfo();
			} else {
				Toast.makeText(this, R.string.bt_not_enabled_leaving, Toast.LENGTH_SHORT).show();
				finish();
			}
			break;
		case REQUEST_SELECT_DEVICE:
			if (resultCode == Activity.RESULT_OK) {
				BluetoothDevice device = data.getParcelableExtra(EXTRA_DEVICE);
				startCommunication(device);
			}
			break;
		}
	}

	// The Handler that gets information back from the BluetoothChatService
	private final Handler mHandler = new Handler() {
		int k=0;
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case MESSAGE_READ:
				Measure[] measures = (Measure[]) msg.obj;
				StringBuilder strBuilder = new StringBuilder();
				for(Measure measure:measures) {
					strBuilder.append(measure);
					strBuilder.append("\n");
					strBuilder.append("\n");
				}
				textOutput.setText(textOutput.getText().toString()+strBuilder.toString());
				break;
			case MESSAGE_CONNECTED:
				k=0;
				String mConnectedDeviceName = msg.getData().getString(DEVICE_NAME);
				Toast.makeText(getApplicationContext(),
						"Connected to " + mConnectedDeviceName,	Toast.LENGTH_SHORT).show();
				break;
			case MESSAGE_CONNECTION_FAILED:
				k++;
				if(k<ATTEMPS){
					BluetoothDevice device = msg.getData().getParcelable(DEVICE);
					mService.receiveData(device);
				} else {
					k=0;
					Toast.makeText(getApplicationContext(),"Can't connect to device", Toast.LENGTH_SHORT).show();
				}					
				break;
			case MESSAGE_CONNECTION_LOST:
				break;
			}
		}
	};
}
